package cn.net.wanji.controller;

import cn.net.wanji.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
@RestController
@RequestMapping(value = "/remove")
public class DirectoryCleanerController {
    @Value(value = "${directoryCleaner.path}")
    private  String mainDir;
    @GetMapping("/removeFile")
    public AjaxResult removeFile(Integer days) throws IOException {
        LocalDateTime currentDate = LocalDateTime.now();
        LocalDateTime oneDayAgo = currentDate.minusDays(days);
        Path dir = Paths.get(mainDir);

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            for (Path path : stream) {
                File file = path.toFile();

                if (file.isDirectory()) {
                    FileTime fileCreationTime = (FileTime) Files.getAttribute(path, "creationTime");
                    LocalDateTime creationDateTime = LocalDateTime.ofInstant(
                            fileCreationTime.toInstant(), ZoneId.systemDefault());

                    if (creationDateTime.isBefore(oneDayAgo)) {
                        deleteDirectory(file);
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    public static void deleteDirectory(File dir) {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                deleteDirectory(file);
            }
        }
        dir.delete();
    }

//    public static void main(String[] args) {
//        try {
//            DirectoryCleanerController directoryCleanerController = new DirectoryCleanerController();
//            directoryCleanerController.removeFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
